﻿using BLL.Services;
using FlowerShop.Core.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FlowerShopMVC.Controllers
{
    public class ProductController : Controller
    {
        private readonly ProductService _productService;

        public ProductController()
        {
            _productService = new ProductService();
        }

        public ActionResult Index()
        {
            var products = _productService.GetAllProducts();
            return View(products);
        }

        public ActionResult Details(int id)
        {
            var product = _productService.GetProductById(id);
            if (product == null)
            {
                return HttpNotFound(); // 使用 ASP.NET MVC 的 HttpNotFound 方法
            }
            return View(product);
        }

        [HttpPost]
        public ActionResult AddToCart(int productId)
        {
            // 获取当前用户ID（假设从Session中获取）
            int userId = Convert.ToInt32(Session["UserId"]); // 替换为实际的用户ID获取方式

            // 获取商品信息
            var product = _productService.GetProductById(productId);
            if (product == null)
            {
                return HttpNotFound();
            }

            // 检查库存是否足够
            if (product.G_kuchun <= 0)
            {
                TempData["Message"] = "商品库存不足！";
                return RedirectToAction("Details", new { id = productId });
            }

            // 将商品加入购物车
            using (var context = new Model1())
            {
                // 检查购物车中是否已存在该商品
                var existingCartItem = context.Tshoppingcars.FirstOrDefault(c => c.t_id == userId && c.G_id == productId);

                if (existingCartItem != null)
                {
                    // 如果已存在，增加数量
                    existingCartItem.kuchun += 1;
                }
                else
                {
                    // 如果不存在，添加新记录
                    context.Tshoppingcars.Add(new Tshoppingcars
                    {
                        t_id = userId,
                        G_id = productId,
                        G_name = product.G_name,
                        jiage = product.G_xiaoshoujia,
                        chebenjia = product.G_chenbenjia,
                        kuchun = 1
                    });
                }

                // 更新库存
                product.G_kuchun -= 1;
                context.SaveChanges();
            }

            // 添加成功消息
            TempData["Message"] = "商品已成功加入购物车！";

            // 重定向到商品列表
            return RedirectToAction("Index");
    }
    }
}
